/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tnviet.proj.jna.table;

import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.UIManager;
import tnviet.proj.jna.JNPacketAnalyzerLoader;
import tnviet.proj.jna.Program;
import tnviet.proj.jna.analyzer.JNPacketAnalyzer;


/**
 *
 * @author Administrator
 */
public class ProtocolColor {

    String protocol;
    Color color;

    public ProtocolColor(String protocol, Color color) {
        this.protocol = protocol;
        this.color = color;
    }

    public Color getColor() {
        return color;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return this.getProtocol();
    }



    public static ProtocolColor[] LoadProtocolColors(){
        JNPacketAnalyzer[] analyzers = JNPacketAnalyzerLoader.getAnalyzers();
        Connection con = Program.connection;
        ProtocolColor[] data = new ProtocolColor[analyzers.length];
        String INSSERT_CMD = "INSERT INTO JNA_COLOR (PROTOCOL, RED, GREEN, BLUE) VALUES(?,?,?,?)";
        String UPDATE_CMD = "UPDATE JNA_COLOR SET RED = ?, GREEN = ?, BLUE = ? WHERE PROTOCOL = ?";
        String SELECT_CMD = "SELECT * FROM JNA_COLOR WHERE PROTOCOL = ?";
        PreparedStatement selectStm;
        Color color = (Color) UIManager.get("Label.background");
        PreparedStatement stm;
        try {
            selectStm = con.prepareStatement(SELECT_CMD);
            stm = con.prepareStatement(INSSERT_CMD);
            for(int i=0; i<analyzers.length;i++){
                ProtocolColor pC = null;
                String protocol = analyzers[i].getProtocolName();
                selectStm.setString(1, protocol);
                ResultSet rs = selectStm.executeQuery();
                if(rs.next()){
                    int red = rs.getInt(3);
                    int green = rs.getInt(4);
                    int blue = rs.getInt(5);
                    Color tempColor = new Color(red, green, blue);
                    pC = new ProtocolColor(protocol, tempColor);
                } else {
                    stm.setString(1, protocol);
                    stm.setInt(2,color.getRed());
                    stm.setInt(3,color.getGreen());
                    stm.setInt(4,color.getBlue());
                    stm.executeUpdate();
                    pC = new ProtocolColor(protocol, color);
                }
                data[i] = pC;
            }
        } catch (SQLException ex) {
        }
        return data;
    }

    

}
